package com.xyz.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xyz.config.SystemData;
import com.xyz.dao.mapper.BusinessFileDaoMapper;
import com.xyz.dao.mapper.UpkeepDaoMapper;
import com.xyz.dao.pojo.BusinessFileVo;
import com.xyz.dto.SelectPageUpkeepDto;
import com.xyz.dto.enums.EnumAcceptBusinessType;
import com.xyz.dto.enums.EnumAnnBusinessType;
import com.xyz.dto.enums.EnumBusinessType;
import com.xyz.dto.enums.EnumRepState;
import com.xyz.entity.mapper.*;
import com.xyz.entity.pojo.*;
import com.xyz.service.CommonService;
import com.xyz.service.UpkeepAppService;
import com.xyz.util.dto.DataResult;
import com.xyz.util.dto.GridData;
import com.xyz.util.dto.LoginInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Transactional(rollbackFor = Exception.class)
public class UpkeepAppServiceImpl implements UpkeepAppService {

    @Autowired
    private CommonService commonService;

    @Autowired
    private UpkeepWorkOrderMapper upkeepWorkOrderMapper;

    @Autowired
    private UpkeepMaintenanceMapper upkeepMaintenanceMapper;

    @Autowired
    private UpkeepTaskMapper upkeepTaskMapper;

    @Autowired
    private UpkeepWorkOrderFlowMapper upkeepWorkOrderFlowMapper;

    @Autowired
    private EquipmentInfoMapper equipmentInfoMapper;

    @Autowired
    private BusinessAnnounceMapper businessAnnounceMapper;

    @Autowired
    private BusinessAcceptMapper businessAcceptMapper;

    @Autowired
    private UpkeepDaoMapper upkeepDaoMapper;

    @Autowired
    private BusinessFileDaoMapper businessFileDao;

    @Autowired
    private SystemEmployeeMapper systemEmployeeMapper;

    /*
     * 列表查询
     * */
    @Override
    public DataResult getUpkeepAll(LoginInfo loginInfo, SelectPageUpkeepDto selectPageUpkeepDto) throws Exception {
        Page<RepairWorkOrder> pageObject = PageHelper.startPage(NumberUtil.parseInt(selectPageUpkeepDto.getPageNum()), NumberUtil.parseInt(selectPageUpkeepDto.getPageSize()));
        //获取数据
        Map<String, Object> paraMap = new HashMap<>();
        if (StrUtil.isNotEmpty(selectPageUpkeepDto.getUpkeepState())) {
            paraMap.put("upkeepState", selectPageUpkeepDto.getUpkeepState());
        }
        if (StrUtil.isNotEmpty(selectPageUpkeepDto.getEmName())) {
            paraMap.put("emName", selectPageUpkeepDto.getEmName());
        }
        if (StrUtil.isNotEmpty(selectPageUpkeepDto.getWorkOrderCode())) {
            paraMap.put("workOrderCode", selectPageUpkeepDto.getWorkOrderCode());
        }
        if (StrUtil.isNotEmpty(selectPageUpkeepDto.getIsMy()) && "2".equals(selectPageUpkeepDto.getIsMy())) {
            paraMap.put("employeeId", loginInfo.getLoginEmployeeId());
        }

        List<UpkeepWorkOrder> upkeepWorkOrderList = upkeepDaoMapper.selectUpkeepWorkOrderList(paraMap);
        List<Map<String, Object>> list = new ArrayList<>();
        for (UpkeepWorkOrder uw : upkeepWorkOrderList) {
            Map<String, Object> map = new HashMap<>();
            map.put("upkeepId", uw.getUpkeepId());
            map.put("workOrderCode", uw.getWorkOrderCode());
            if (uw.getEmployeeId() == 0) {
                map.put("employeeName", "计划创建");
            } else {
                map.put("employeeName", commonService.getEmployeeNameById(uw.getEmployeeId()));
            }
            map.put("emName", uw.getEmName());
            map.put("upkeepState", uw.getUpkeepState());
            map.put("createTime", DateUtil.format(uw.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
            // 添加导出所需新的字段
            map.put("upkeepStartTime", uw.getUpkeepStartTime());
            map.put("emCode", uw.getEmCode());
            map.put("emSpecification", uw.getEmSpecification());
            map.put("emLocation", uw.getEmLocation());
            list.add(map);
        }
        //分页总数
        GridData gridData = new GridData(pageObject.getTotal(), list);
        return DataResult.build9100(gridData);
    }

    /*
     * App列表查询
     * */
    @Override
    public DataResult getPendingUpkeepAll(LoginInfo loginInfo, SelectPageUpkeepDto selectPageUpkeepDto) throws Exception {
        Page<RepairWorkOrder> pageObject = PageHelper.startPage(NumberUtil.parseInt(selectPageUpkeepDto.getPageNum()), NumberUtil.parseInt(selectPageUpkeepDto.getPageSize()));
        if (StrUtil.isBlank(selectPageUpkeepDto.getUpkeepState())) {
            return DataResult.build9200("upkeepState");
        }
        UpkeepWorkOrderExample keepExample = new UpkeepWorkOrderExample();
        UpkeepWorkOrderExample.Criteria keepCriteria = keepExample.createCriteria();
        int state = Integer.parseInt(selectPageUpkeepDto.getUpkeepState());
        subRepCriteria1(selectPageUpkeepDto, keepCriteria);
        if (EnumRepState.INVALID.getRepState() == state) {
            keepCriteria.andUpkeepStateEqualTo(state);
        } else if (EnumRepState.PENDING_ANNOUNCE.getRepState() == state) {
            keepCriteria.andUpkeepStateEqualTo(state);
        } else if (EnumRepState.PENDING_RECEIVE.getRepState() == state) {
            keepCriteria.andUpkeepStateEqualTo(state);
        } else if (EnumRepState.PENDING_REFUSE.getRepState() == state) {
            List<Integer> stateIn = new ArrayList<>();
            stateIn.add(EnumRepState.PENDING_RECEIVE.getRepState());
            stateIn.add(EnumRepState.PENDING_REFUSE.getRepState());
            stateIn.add(EnumRepState.PENDING_TRANSFER.getRepState());
            keepCriteria.andUpkeepStateIn(stateIn);
        } else if (EnumRepState.ACCEPTED_NO.getRepState() == state) {
            keepCriteria.andUpkeepStateEqualTo(state);
        } else if (EnumRepState.ACCEPTED_YES.getRepState() == state) {
            keepCriteria.andUpkeepStateEqualTo(state);
            keepCriteria.andAcceptEmployeeIdEqualTo(loginInfo.getLoginEmployeeId());
        } else if (EnumRepState.ALLOCATED.getRepState() == state) {
            List<Integer> stateIn = new ArrayList<>();
            stateIn.add(EnumRepState.ALLOCATED.getRepState());
            stateIn.add(EnumRepState.UNDE_REPAIR.getRepState());
            stateIn.add(EnumRepState.SUSPEND_REPAIR.getRepState());
            keepCriteria.andUpkeepStateIn(stateIn);
            keepCriteria.andMaintenEmployeeIdEqualTo(loginInfo.getLoginEmployeeId());
        } else if (EnumRepState.MAINTENANCE_YES.getRepState() == state) {
            List<Integer> stateIn = new ArrayList<>();
            stateIn.add(EnumRepState.INVALID.getRepState());
            stateIn.add(EnumRepState.MAINTENANCE_YES.getRepState());
            keepCriteria.andUpkeepStateIn(stateIn);
            keepCriteria.andEmployeeIdEqualTo(loginInfo.getLoginEmployeeId());
            UpkeepWorkOrderExample.Criteria keepCriteria2 = keepExample.or();
            subRepCriteria1(selectPageUpkeepDto, keepCriteria2);
            keepCriteria2.andUpkeepStateIn(stateIn);
            keepCriteria2.andAnnounceEmployeeIdEqualTo(loginInfo.getLoginEmployeeId());
            UpkeepWorkOrderExample.Criteria keepCriteria3 = keepExample.or();
            subRepCriteria1(selectPageUpkeepDto, keepCriteria3);
            keepCriteria3.andUpkeepStateEqualTo(EnumRepState.MAINTENANCE_YES.getRepState());
            keepCriteria3.andMaintenEmployeeIdEqualTo(loginInfo.getLoginEmployeeId());
            UpkeepWorkOrderExample.Criteria keepCriteria4 = keepExample.or();
            subRepCriteria1(selectPageUpkeepDto, keepCriteria4);
            keepCriteria4.andUpkeepStateEqualTo(EnumRepState.MAINTENANCE_YES.getRepState());
            keepCriteria4.andAcceptEmployeeIdEqualTo(loginInfo.getLoginEmployeeId());
        }
        keepExample.setOrderByClause("create_time desc");
        List<UpkeepWorkOrder> keepWorkList = upkeepWorkOrderMapper.selectByExample(keepExample);
        Map<Long, EquipmentTree> equipmentTreeMap = commonService.getEquipmentTreeMap();
        //获取数据
        List<Map<String, Object>> list = new ArrayList<>();
        for (UpkeepWorkOrder rw : keepWorkList) {
            Map<String, Object> map = new HashMap<>();
            map.put("upkeepId", rw.getUpkeepId());
            map.put("workOrderCode", rw.getWorkOrderCode());
            if (rw.getEmployeeId() == 0) {
                map.put("employeeName", "计划创建");
            } else {
                map.put("employeeName", commonService.getEmployeeNameById(rw.getEmployeeId()));
            }
            map.put("emName", rw.getEmName());
            map.put("emLocation", rw.getEmLocation());
            map.put("upkeepState", rw.getUpkeepState());
            map.put("treeName", commonService.getTreeStrById(equipmentTreeMap,rw.getTreeId()));
            map.put("createTime", DateUtil.format(rw.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
            list.add(map);
        }
        //分页总数
        GridData gridData = new GridData(pageObject.getTotal(), list);
        return DataResult.build9100(gridData);
    }

    /*
     * 根据Id查询维保详情
     * */
    @Override
    public DataResult getUpkeepBasisById(LoginInfo loginInfo, String upkeepId) throws Exception {
        Map<String, Object> map = new HashMap<>();
        long upkeepIdLong = Long.parseLong(upkeepId);
        UpkeepWorkOrder upkeepWorkOrder = upkeepWorkOrderMapper.selectByPrimaryKey(upkeepIdLong);
        if (upkeepWorkOrder == null) {
            return DataResult.build9100(map);
        }
        //获取设备信息
        map.put("upkeepId", upkeepWorkOrder.getUpkeepId());
        map.put("workOrderCode", upkeepWorkOrder.getWorkOrderCode());
        map.put("upkeepState", upkeepWorkOrder.getUpkeepState());
        map.put("upkeepStartTime", DateUtil.format(upkeepWorkOrder.getUpkeepStartTime(), DatePattern.NORM_DATE_PATTERN));
        EquipmentInfo equipmentInfo = null;
        if (upkeepWorkOrder.getEmId() != 0) {
            equipmentInfo = equipmentInfoMapper.selectByPrimaryKey(upkeepWorkOrder.getEmId());
        }
        if (equipmentInfo != null) {
            Map<Integer, String> typeEmGradeMap = commonService.getDictMap("TYPE_EM_GRADE");
            map.put("emName", equipmentInfo.getEmName());
            map.put("emCode", equipmentInfo.getEmCode());
            map.put("emGrade", typeEmGradeMap.get(equipmentInfo.getEmGrade()));
            map.put("emLocation", equipmentInfo.getEmLocation());
            map.put("emSpecification", equipmentInfo.getEmSpecification());
        } else {
            map.put("emName", upkeepWorkOrder.getEmName());
            map.put("emCode", upkeepWorkOrder.getEmCode());
            map.put("emGrade", "");
            map.put("emLocation", upkeepWorkOrder.getEmLocation());
            map.put("emSpecification", upkeepWorkOrder.getEmSpecification());
        }
        UpkeepTaskExample taskExample = new UpkeepTaskExample();
        taskExample.createCriteria().andUpkeepIdEqualTo(upkeepWorkOrder.getUpkeepId());
        List<UpkeepTask> upkeepTasks = upkeepTaskMapper.selectByExample(taskExample);
        List<Map<String, Object>> upkeepTaskList = new ArrayList<>();
        for (UpkeepTask upkeepTask : upkeepTasks) {
            Map<String, Object> upkeepTaskMap = new HashMap<>();
            upkeepTaskMap.put("id", upkeepTask.getId());
            upkeepTaskMap.put("taskId", upkeepTask.getTaskId());
            upkeepTaskMap.put("taskName", upkeepTask.getTaskName());
            upkeepTaskMap.put("taskDesc", upkeepTask.getTaskDesc());
            upkeepTaskMap.put("remark", upkeepTask.getRemark());
            upkeepTaskMap.put("precautions", upkeepTask.getPrecautions());
            upkeepTaskMap.put("isComplete", upkeepTask.getIsComplete());
            upkeepTaskList.add(upkeepTaskMap);
        }
        List<Map<String, Object>> upkeepPartList = upkeepDaoMapper.selectUpkeepPartList(upkeepWorkOrder.getUpkeepId());
        map.put("taskList", upkeepTaskList);
        map.put("partList", upkeepPartList);
        int upkeepStateInt = upkeepWorkOrder.getUpkeepState();
        boolean isFlag = false;

        UpkeepMaintenanceExample keepMainExample = new UpkeepMaintenanceExample();
        UpkeepMaintenanceExample.Criteria keepMainCriteria = keepMainExample.createCriteria();
        keepMainCriteria.andUpkeepIdEqualTo(upkeepIdLong);
        keepMainCriteria.andMtcStateEqualTo(upkeepStateInt);
        keepMainExample.setOrderByClause("create_time desc limit 1");
        List<UpkeepMaintenance> upkeepMaintenanceList = upkeepMaintenanceMapper.selectByExample(keepMainExample);
        Long maintenanceId = null;

        if (CollUtil.isNotEmpty(upkeepMaintenanceList)) {
            UpkeepMaintenance upkeepMaintenance = upkeepMaintenanceList.get(0);
            maintenanceId = upkeepMaintenance.getId();
            if (upkeepStateInt == EnumRepState.ALLOCATED.getRepState()
                    || upkeepStateInt == EnumRepState.UNDE_REPAIR.getRepState()
                    || upkeepStateInt == EnumRepState.SUSPEND_REPAIR.getRepState()) {
                //已分配和维修中
                if (loginInfo.getLoginEmployeeId().equals(upkeepMaintenance.getEmployeeId())) {
                    isFlag = true;
                }
            }

            if (upkeepStateInt == EnumRepState.ACCEPTED_YES.getRepState()) {
                if (loginInfo.getLoginEmployeeId().equals(upkeepMaintenance.getAcceptEmployeeId())) {
                    isFlag = true;
                }
            }
        }
        /*根据repairWorkOrder的mainten_employee_users_id查询到员工列表数据*/
        List<SystemEmployee> employeeList = systemEmployeeMapper.roleList();
        List<SystemEmployee> filteredEmployees = null;
        if (upkeepWorkOrder.getMaintenEmployeeUsersId() != null && !upkeepWorkOrder.getMaintenEmployeeUsersId().isEmpty()) {
            String[] maintenEmployeeUserIds = upkeepWorkOrder.getMaintenEmployeeUsersId().split(",");
            // 将字符串数组转换为Set，以便进行快速查找
            Set<Long> maintenEmployeeUserIdSet = Arrays.stream(maintenEmployeeUserIds)
                    .filter(item -> !item.equals("null"))
                    .map(String::trim) // 去除可能的空格
                    .map(Long::parseLong) // 将字符串转换为Long类型
                    .collect(Collectors.toSet());
            // 使用Stream API过滤employeeList
            filteredEmployees = employeeList.stream()
                    .filter(employee -> maintenEmployeeUserIdSet.contains(employee.getId()))
                    .collect(Collectors.toList());
        }
        map.put("flag", isFlag);
        map.put("maintenanceId", maintenanceId);
        map.put("selectedItems", filteredEmployees);
        return DataResult.build9100(map);
    }

    @Override
    public DataResult getUpkeepBasisUpdateById(LoginInfo loginInfo, String upkeepId, String maintenEmployeeUsersId) throws Exception {
        int rows = upkeepWorkOrderMapper.updateById(Long.valueOf(upkeepId), maintenEmployeeUsersId);
        return DataResult.build9100(rows);
    }

    /*
     * 根据Id查询审核信息
     * */
    @Override
    public DataResult getAnnounceUpkeepById(LoginInfo loginInfo, String upkeepId) throws Exception {
        long upkeepIdLong = Long.parseLong(upkeepId);
        UpkeepWorkOrder upkeepWorkOrder = upkeepWorkOrderMapper.selectByPrimaryKey(upkeepIdLong);
        if (upkeepWorkOrder == null) {
            return DataResult.build9100(new HashMap<>());
        }
        int upkeepStateInt = upkeepWorkOrder.getUpkeepState();
        //待审核没有信息
        if (upkeepStateInt == EnumRepState.PENDING_ANNOUNCE.getRepState()) {
            return DataResult.build9100(new HashMap<>());
        }

        Map<String, Object> announceMap = getAnnounceUpkeepMap(upkeepIdLong);
        announceMap.put("estimatedWorkHour", upkeepWorkOrder.getEstimatedWorkHour());

        if (upkeepStateInt == EnumRepState.INVALID.getRepState() || upkeepStateInt == EnumRepState.PENDING_RECEIVE.getRepState()
                || upkeepStateInt == EnumRepState.PENDING_REFUSE.getRepState() || upkeepStateInt == EnumRepState.PENDING_TRANSFER.getRepState()) {
            announceMap.put("disEmployeeName", "");
            announceMap.put("disTime", "");
            return DataResult.build9100(announceMap);
        }

        UpkeepMaintenanceExample keepMainExample = new UpkeepMaintenanceExample();
        UpkeepMaintenanceExample.Criteria keepMainCriteria = keepMainExample.createCriteria();
        keepMainCriteria.andUpkeepIdEqualTo(upkeepIdLong);
        keepMainCriteria.andMtcStateEqualTo(upkeepStateInt);
        keepMainExample.setOrderByClause("create_time desc limit 1");
        List<UpkeepMaintenance> upkeepMaintenanceList = upkeepMaintenanceMapper.selectByExample(keepMainExample);
        if (CollUtil.isEmpty(upkeepMaintenanceList)) {
            announceMap.put("disEmployeeName", "");
            announceMap.put("disTime", "");
            return DataResult.build9100(announceMap);
        }
        //派生信息获取开始
        UpkeepMaintenance upkeepMaintenance = upkeepMaintenanceList.get(0);
        announceMap.put("disTime", DateUtil.format(upkeepMaintenance.getDisTime(), "yyyy-MM-dd HH:mm:ss"));
        //维修人员
        if (upkeepMaintenance.getDisType() == 1) {
            announceMap.put("disEmployeeName", "系统自动分配");
        } else if (upkeepMaintenance.getDisType() == 2) {
            String disEmployeeName = commonService.getEmployeeNameById(upkeepMaintenance.getDisEmployeeId());
            if (StrUtil.isNotBlank(disEmployeeName)) {
                announceMap.put("disEmployeeName", disEmployeeName + "自己领取");
            } else {
                announceMap.put("disEmployeeName", "");
            }
        } else if (upkeepMaintenance.getDisType() == 3) {
            announceMap.put("disEmployeeName", commonService.getEmployeeNameById(upkeepMaintenance.getDisEmployeeId()));
        } else {
            announceMap.put("disEmployeeName", "");
        }
        return DataResult.build9100(announceMap);
    }

    /*
     * 根据Id查询报保审维修信息
     * */
    @Override
    public DataResult getMaintenanceUpkeepById(LoginInfo loginInfo, String upkeepId) throws Exception {
        Map<String, Object> maintenanceMap = new HashMap<>();
        long upkeepIdLong = Long.parseLong(upkeepId);
        UpkeepWorkOrder upkeepWorkOrder = upkeepWorkOrderMapper.selectByPrimaryKey(upkeepIdLong);
        if (upkeepWorkOrder == null) {
            return DataResult.build9100(new HashMap<>());
        }
        int upkeepStateInt = upkeepWorkOrder.getUpkeepState();
        if (upkeepStateInt == EnumRepState.INVALID.getRepState() || upkeepStateInt == EnumRepState.PENDING_ANNOUNCE.getRepState()
                || upkeepStateInt == EnumRepState.PENDING_RECEIVE.getRepState() || upkeepStateInt == EnumRepState.PENDING_REFUSE.getRepState()
                || upkeepStateInt == EnumRepState.PENDING_TRANSFER.getRepState()) {
            return DataResult.build9100(maintenanceMap);
        }

        UpkeepMaintenanceExample keepMainExample = new UpkeepMaintenanceExample();
        UpkeepMaintenanceExample.Criteria keepMainCriteria = keepMainExample.createCriteria();
        keepMainCriteria.andUpkeepIdEqualTo(upkeepIdLong);
        keepMainCriteria.andMtcStateEqualTo(upkeepStateInt);
        keepMainExample.setOrderByClause("create_time desc limit 1");
        List<UpkeepMaintenance> upkeepMaintenanceList = upkeepMaintenanceMapper.selectByExample(keepMainExample);
        if (CollUtil.isEmpty(upkeepMaintenanceList)) {
            return DataResult.build9100(maintenanceMap);
        }
        UpkeepMaintenance upkeepMaintenance = upkeepMaintenanceList.get(0);

        //维修信息获取开始
        maintenanceMap.put("remark", upkeepMaintenance.getRemark());
        maintenanceMap.put("employeeName", commonService.getEmployeeNameById(upkeepMaintenance.getEmployeeId()));
        maintenanceMap.put("id", upkeepMaintenance.getId());
        maintenanceMap.put("isReuse", upkeepMaintenance.getIsReuse());
        if (upkeepStateInt != EnumRepState.ALLOCATED.getRepState()) {
            maintenanceMap.put("mtcStartTime", DateUtil.format(upkeepMaintenance.getMtcStartTime(), "yyyy-MM-dd HH:mm:ss"));
        } else {
            maintenanceMap.put("mtcStartTime", "");
        }

        getMaintenanceFileList(maintenanceMap, upkeepMaintenance.getId());

        if (upkeepStateInt == EnumRepState.ALLOCATED.getRepState()
                || upkeepStateInt == EnumRepState.UNDE_REPAIR.getRepState()
                || upkeepStateInt == EnumRepState.SUSPEND_REPAIR.getRepState()) {
            //已分配和维修中
            if (loginInfo.getLoginEmployeeId().equals(upkeepMaintenance.getEmployeeId())) {
                maintenanceMap.put("flag", true);
            } else {
                maintenanceMap.put("flag", false);
            }
            return DataResult.build9100(maintenanceMap);
        }
        maintenanceMap.put("mtcEndTime", DateUtil.format(upkeepMaintenance.getMtcEndTime(), "yyyy-MM-dd HH:mm:ss"));

        //计算后维修的时间
        int isReuse = upkeepMaintenance.getIsReuse();
        long countMtcSecond = 0;
        long suspendSecond = 0;
        if (isReuse == 1) {
            countMtcSecond = upkeepMaintenance.getMtcSecond();
            suspendSecond = upkeepMaintenance.getSuspendSecond();
        } else if (isReuse == 2 && StrUtil.isNotBlank(upkeepMaintenance.getAssMtcId())) {
            //多次维修

            UpkeepMaintenanceExample isReuseMainExample = new UpkeepMaintenanceExample();
            UpkeepMaintenanceExample.Criteria isReuseMainCriteria = isReuseMainExample.createCriteria();
            String assMtcId = upkeepMaintenance.getAssMtcId();
            if (assMtcId.contains(",")) {
                String[] split = assMtcId.split(",");
                List<Long> idList = new ArrayList<>();
                for (String sp : split) {
                    if (StrUtil.isNotBlank(sp)) {
                        idList.add(Long.parseLong(sp));
                    }
                }
                isReuseMainCriteria.andIdIn(idList);
                List<UpkeepMaintenance> isReuseMaintenanceList = upkeepMaintenanceMapper.selectByExample(isReuseMainExample);
                countMtcSecond = upkeepMaintenance.getMtcSecond();
                suspendSecond = upkeepMaintenance.getSuspendSecond();
                for (UpkeepMaintenance forMaintenance : isReuseMaintenanceList) {
                    countMtcSecond += forMaintenance.getMtcSecond();
                    suspendSecond += forMaintenance.getSuspendSecond();
                }
            } else {
                UpkeepMaintenance isReuseMaintenance = upkeepMaintenanceMapper.selectByPrimaryKey(Long.parseLong(assMtcId));
                countMtcSecond = upkeepMaintenance.getMtcSecond() + isReuseMaintenance.getMtcSecond();
                suspendSecond = upkeepMaintenance.getSuspendSecond() + isReuseMaintenance.getSuspendSecond();
            }
        }

        String countMtcSecondStr = getTimeStr(countMtcSecond);
        String suspendSecondStr = getTimeStr(suspendSecond);

        if (countMtcSecond <= 0) {
            maintenanceMap.put("mtcSecond", "");
        } else {
            maintenanceMap.put("mtcSecond", countMtcSecondStr);
        }

        if (suspendSecond <= 0) {
            maintenanceMap.put("suspendSecond", "无");
        } else {
            maintenanceMap.put("suspendSecond", suspendSecondStr);
        }

        return DataResult.build9100(maintenanceMap);
    }

    /*
     * 根据Id查询验收信息
     * */
    @Override
    public DataResult getAcceptUpkeepById(LoginInfo loginInfo, String upkeepId) throws Exception {
        Map<String, Object> acceptMap = new HashMap<>();
        long upkeepIdLong = Long.parseLong(upkeepId);
        UpkeepWorkOrder upkeepWorkOrder = upkeepWorkOrderMapper.selectByPrimaryKey(upkeepIdLong);
        if (upkeepWorkOrder == null) {
            return DataResult.build9100(new HashMap<>());
        }
        int upkeepStateInt = upkeepWorkOrder.getUpkeepState();
        if (upkeepStateInt == EnumRepState.INVALID.getRepState() || upkeepStateInt == EnumRepState.PENDING_ANNOUNCE.getRepState()
                || upkeepStateInt == EnumRepState.PENDING_RECEIVE.getRepState() || upkeepStateInt == EnumRepState.PENDING_REFUSE.getRepState()
                || upkeepStateInt == EnumRepState.PENDING_TRANSFER.getRepState()) {
            return DataResult.build9100(acceptMap);
        }

        if (upkeepStateInt == EnumRepState.ALLOCATED.getRepState() || upkeepStateInt == EnumRepState.UNDE_REPAIR.getRepState()
                || upkeepStateInt == EnumRepState.SUSPEND_REPAIR.getRepState() || upkeepStateInt == EnumRepState.ACCEPTED_NO.getRepState()) {
            return DataResult.build9100(acceptMap);
        }

        UpkeepMaintenanceExample keepMainExample = new UpkeepMaintenanceExample();
        UpkeepMaintenanceExample.Criteria keepMainCriteria = keepMainExample.createCriteria();
        keepMainCriteria.andUpkeepIdEqualTo(upkeepIdLong);
        keepMainCriteria.andMtcStateEqualTo(upkeepStateInt);
        keepMainExample.setOrderByClause("create_time desc limit 1");
        List<UpkeepMaintenance> upkeepMaintenanceList = upkeepMaintenanceMapper.selectByExample(keepMainExample);
        if (CollUtil.isEmpty(upkeepMaintenanceList)) {
            return DataResult.build9100(acceptMap);
        }

        if (upkeepStateInt == EnumRepState.ACCEPTED_YES.getRepState()) {
            if (upkeepMaintenanceList.get(0).getAcceptEmployeeId() != null) {
                acceptMap.put("employeeName", commonService.getEmployeeNameById(upkeepMaintenanceList.get(0).getAcceptEmployeeId()));
                return DataResult.build9100(acceptMap);
            }
        }

        BusinessAcceptExample accExample = new BusinessAcceptExample();
        BusinessAcceptExample.Criteria accCriteria = accExample.createCriteria();
        accCriteria.andSourceIdEqualTo(upkeepMaintenanceList.get(0).getId());
        accCriteria.andBusTypeEqualTo(EnumAcceptBusinessType.UPKEEPMAINTENANCE.getBusType());
        accExample.setOrderByClause("create_time desc limit 1");
        List<BusinessAccept> businessAccepts = businessAcceptMapper.selectByExample(accExample);
        if (CollUtil.isNotEmpty(businessAccepts)) {
            BusinessAccept businessAccept = businessAccepts.get(0);
            if (1 == businessAccept.getAcceptState()) {
                acceptMap.put("acceptStateName", "验收通过");
            } else if (2 == businessAccept.getAcceptState()) {
                acceptMap.put("acceptStateName", "验收驳回");
            }
            acceptMap.put("employeeName", commonService.getEmployeeNameById(businessAccept.getEmployeeId()));
            acceptMap.put("acceptExplain", businessAccept.getAcceptExplain());
            acceptMap.put("acceptScore", businessAccept.getAcceptScore());
            acceptMap.put("acceptTime", DateUtil.format(businessAccept.getAcceptTime(), "yyyy-MM-dd HH:mm:ss"));
        }
        return DataResult.build9100(acceptMap);
    }

    /*
     * 工单流水
     * */
    @Override
    public DataResult getUpkeepWorkOrderFlow(LoginInfo loginInfo, String upkeepId) throws Exception {
        UpkeepWorkOrderFlowExample flowExample = new UpkeepWorkOrderFlowExample();
        UpkeepWorkOrderFlowExample.Criteria flowCriteria = flowExample.createCriteria();
        flowCriteria.andUpkeepIdEqualTo(Long.parseLong(upkeepId));
        flowExample.setOrderByClause("create_time desc");
        List<UpkeepWorkOrderFlow> upkeepWorkOrderFlowFlows = upkeepWorkOrderFlowMapper.selectByExample(flowExample);
        List<Map<String, Object>> flowList = new ArrayList<>();
        for (UpkeepWorkOrderFlow upkeepWorkOrderFlow : upkeepWorkOrderFlowFlows) {
            Map<String, Object> map = new HashMap<>();
            map.put("sourceId", upkeepWorkOrderFlow.getSourceId());
            map.put("flowDesc", upkeepWorkOrderFlow.getFlowDesc());
            map.put("flowType", upkeepWorkOrderFlow.getFlowType());
            map.put("employeeName", commonService.getEmployeeNameById(upkeepWorkOrderFlow.getEmployeeId()));
            if (upkeepWorkOrderFlow.getDisEmployeeId() != 0) {
                map.put("disEmployeeName", commonService.getEmployeeNameById(upkeepWorkOrderFlow.getDisEmployeeId()));
            } else {
                map.put("disEmployeeName", "");
            }
            map.put("createTime", DateUtil.format(upkeepWorkOrderFlow.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
            flowList.add(map);
        }
        return DataResult.build9100(flowList);
    }

    private String getTimeStr(long timeSecond) {
        String strTimeSecond = "";
        long second = timeSecond % 60;
        long minutes = TimeUnit.SECONDS.toMinutes(timeSecond);
        if (minutes == 0) {
            strTimeSecond = second + "秒";
        } else if (second == 0) {
            strTimeSecond = minutes + "分";
        } else {
            strTimeSecond = minutes + "分" + second + "秒";
        }
        return strTimeSecond;
    }


    //审核信息MAP
    private Map<String, Object> getAnnounceUpkeepMap(Long upkeepId) {
        Map<String, Object> announceMap = new HashMap<>();
        BusinessAnnounceExample busExample = new BusinessAnnounceExample();
        BusinessAnnounceExample.Criteria busCriteria = busExample.createCriteria();
        busCriteria.andSourceIdEqualTo(upkeepId);
        busCriteria.andBusTypeEqualTo(EnumAnnBusinessType.UPKEEP.getBusType());
        busExample.setOrderByClause("create_time desc limit 1");
        List<BusinessAnnounce> businessAnnounces = businessAnnounceMapper.selectByExample(busExample);
        if (CollUtil.isNotEmpty(businessAnnounces)) {
            BusinessAnnounce businessAnnounce = businessAnnounces.get(0);
            //1审核通过；0审核驳回
            if (businessAnnounce.getAnnState() == 1) {
                announceMap.put("annStateName", "审核通过");
            } else {
                announceMap.put("annStateName", "审核驳回");
            }
            announceMap.put("annState", businessAnnounce.getAnnState());
            announceMap.put("annExplain", businessAnnounce.getAnnExplain());
            announceMap.put("annTime", DateUtil.format(businessAnnounce.getAnnTime(), "yyyy-MM-dd HH:mm:ss"));
            announceMap.put("employeeName", commonService.getEmployeeNameById(businessAnnounce.getEmployeeId()));
        }
        return announceMap;
    }

    private void getMaintenanceFileList(Map<String, Object> map, Long busTablesId) {
        List<BusinessFileVo> businessFileList = businessFileDao.selectBusinessFileByCodes(busTablesId, EnumBusinessType.UPKEEPMAINTENANCE.getBusType());

        List<Map<String, String>> picOldList = new ArrayList<>();
        List<Map<String, String>> audioOldList = new ArrayList<>();
        List<Map<String, String>> videoOldList = new ArrayList<>();
        List<Map<String, String>> picNewList = new ArrayList<>();
        List<Map<String, String>> audioNewList = new ArrayList<>();
        List<Map<String, String>> videoNewList = new ArrayList<>();
        int i = 1;
        int j = 1;
        for (BusinessFileVo vo : businessFileList) {
            /*
             * FileGroup: 2,维修前的文件，3，维修后的文件
             * fileType： 1,图片pic,2音频audio，3，视频video'
             * */
            if (vo.getFileGroup() == 2) {
                if (1 == vo.getFileType()) {
                    Map<String, String> picOldMap = new HashMap<>();
                    picOldMap.put("fileCode", vo.getFileCode());
                    picOldMap.put("fileName", vo.getFileName());
                    picOldList.add(picOldMap);
                } else if (2 == vo.getFileType()) {
                    Map<String, String> audioOldMap = new HashMap<>();
                    audioOldMap.put("fileCode", vo.getFileCode());
                    if (StrUtil.isBlank(vo.getFileName())) {
                        audioOldMap.put("fileName", "");
                    } else {
                        audioOldMap.put("fileName", "音频" + i + vo.getFileName().substring(vo.getFileName().lastIndexOf(".")));
                    }
                    audioOldList.add(audioOldMap);
                    i++;
                } else if (3 == vo.getFileType()) {
                    Map<String, String> videoOldMap = new HashMap<>();
                    videoOldMap.put("fileCode", vo.getFileCode());
                    videoOldMap.put("fileName", vo.getFileName());
                    videoOldList.add(videoOldMap);
                }
            } else if (vo.getFileGroup() == 3) {
                if (1 == vo.getFileType()) {
                    Map<String, String> picNewMap = new HashMap<>();
                    picNewMap.put("fileCode", vo.getFileCode());
                    picNewMap.put("fileName", vo.getFileName());
                    picNewList.add(picNewMap);
                } else if (2 == vo.getFileType()) {
                    Map<String, String> audioNewMap = new HashMap<>();
                    audioNewMap.put("fileCode", vo.getFileCode());

                    if (StrUtil.isBlank(vo.getFileName())) {
                        audioNewMap.put("fileName", "");
                    } else {
                        audioNewMap.put("fileName", "音频" + j + vo.getFileName().substring(vo.getFileName().lastIndexOf(".")));
                    }
                    audioNewList.add(audioNewMap);
                    j++;
                } else if (3 == vo.getFileType()) {
                    Map<String, String> videoNewMap = new HashMap<>();
                    videoNewMap.put("fileCode", vo.getFileCode());
                    videoNewMap.put("fileName", vo.getFileName());
                    videoNewList.add(videoNewMap);
                }
            }
        }
/*        map.put("picOldList",picOldList);
        map.put("audioOldList",audioOldList);
        map.put("videoOldList",videoOldList);*/
        map.put("picNewList", picNewList);
        map.put("audioNewList", audioNewList);
        map.put("videoNewList", videoNewList);
    }


    private void subRepCriteria1(SelectPageUpkeepDto dto, UpkeepWorkOrderExample.Criteria criteria) throws Exception {
        if (StrUtil.isNotEmpty(dto.getWorkOrderCode())) {
            criteria.andWorkOrderCodeLike("%" + dto.getWorkOrderCode() + "%");
        }

        if (StrUtil.isNotEmpty(dto.getEmName())) {
            criteria.andEmNameLike("%" + dto.getEmName() + "%");
        }



        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (StrUtil.isNotEmpty(dto.getStartTime())) {
            criteria.andCreateTimeGreaterThanOrEqualTo(sdf.parse(dto.getStartTime() + " 00:00:00"));
        }

        if (StrUtil.isNotEmpty(dto.getEndTime())) {
            criteria.andCreateTimeLessThanOrEqualTo(sdf.parse(dto.getEndTime() + " 23:59:59"));
        }
    }
}
